package com.sunky.rfidapp.V2

import android.app.DatePickerDialog
import android.content.Intent
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.sunky.db.model.CheckRecord
import com.sunky.db.util.DBManager
import com.sunky.db.util.getAll
import com.sunky.rfidapp.BaseActivity
import com.sunky.rfidapp.R
import com.sunky.rfidapp.model.JsonBase
import com.sunky.rfidapp.network.NetBuilder
import com.sunky.rfidapp.network.RequestManager
import com.sunky.rfidapp.util.showDatePickerDialog
import com.sunky.rfidapp.util.showException
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_check_equip.*
import kotlinx.android.synthetic.main.layout_title.*
import java.text.SimpleDateFormat
import java.util.*

class CheckEquipActivityV2 : BaseActivity() {
//    private val types = arrayOf("装备月份点验", "通信车辆点验", "通信车辆逐车点验", "通信单装点验", "逐批装备点验")
    var selectedType: Int = 0 //选择类型
//    private val seasons = arrayOf("一季度", "二季度", "三季度", "四季度")
    var selectedSeason: Int = -1
    var calendar : Calendar = Calendar.getInstance()

    override fun getLayoutId(): Int {
        return R.layout.activity_check_equip
    }

    override fun initView() {
        TvTitle.text = "装备点验"
//        TvCheckType.setOnClickListener {
//            showSingleChoiceDialog(types[selectedType], types, DialogInterface.OnClickListener { dialogInterface, i ->
//                TvCheckType.text = types[i]
//                selectedType = i
//                TvCheckDate.text = ""
//            })
//        }
        TvCheckType.text = "年度点验"
        TvCheckDate.setOnClickListener {
//            if (selectedType != 0) {
//                if (selectedSeason == -1) {
//                    var month = calendar.get(Calendar.MONTH)
//                    selectedSeason = month / 3
//                }
//                showSingleChoiceDialog(seasons[selectedSeason], seasons, DialogInterface.OnClickListener { dialogInterface, i ->
//                    TvCheckDate.text = seasons[i]
//                    selectedSeason = i
//                })
//            } else {
                showDatePickerDialog(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH), DatePickerDialog.OnDateSetListener { _, year, month, day ->
                    this@CheckEquipActivityV2.calendar.set(Calendar.YEAR,year)
                    this@CheckEquipActivityV2.calendar.set(Calendar.MONTH,month)
                    this@CheckEquipActivityV2.calendar.set(Calendar.DAY_OF_MONTH,day)
                    TvCheckDate.text = getFormatDate()
                })
//            }
        }

        //上传结果
        TvUpload.setOnClickListener {
            if (validate()) {
                toast("开始上传点验数据")
                Observable.create<List<CheckRecord>> {
                    it.onNext(DBManager.getInstance().getAll(checkRecordDao) ?: listOf())
                }.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnNext {
                            if (it.isEmpty()){
                                toast("暂无点验数据，请先点验")
                            }
                        }
                        .doOnError {
                            it.printStackTrace()
                            toast("暂无点验数据，请先点验")
                            showException(it)
                        }
                        .observeOn(Schedulers.io())
                        .flatMap {
                            if (it.isEmpty()) {
                                null
                            } else {
//                                var uploadList = it.map {
//                                    var item = UploadItem(it.id.toString(),it.datetime,it.state)
//                                    item
//                                }
                                var sb = StringBuilder()
                                it.forEach{
                                    sb.append("@")
                                            .append(it.id)
                                            .append(";")
                                            .append(it.datetime)
                                            .append(";")
                                            .append(it.state)
                                }
                                sb.deleteCharAt(0)
                                var date = if (selectedType == 0) TvCheckDate.text.toString()
                                else (selectedSeason + 1).toString()
                                RequestManager.create().uploadCheckResult(
                                        "setCheckList",
                                        NetBuilder.sCode,
                                        selectedType.toString(),
                                        date,
                                        EtCheckPerson.text.toString(),
//                                        Gson().toJson(uploadList).toString()
                                        sb.toString()
                                )
//                                RequestManager.create().getEquipList("getequiplist",NetBuilder.sCode)
                            }
                        }
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            Log.e("Upload","result $it")
                            try {
                                var json = Gson().fromJson(it, JsonBase::class.java)
                                if ("ok" == json.resultCode) {
                                    toast("上传成功")
                                } else {
                                    toast("上传失败，错误原因：" + json.memo)
                                }
                            }catch (it : Exception){
                                toast("上传失败")
                                showException(it)
                            }
                        }, {
                            it.printStackTrace()
                            toast("上传失败，请检查网络")
                            showException(it)
                        })

            }
        }

        TvUpload.visibility = View.GONE//隐藏上报

        //开始点验
        TvStart.setOnClickListener {
            if (validate()) {
                var intent = Intent(this, EquipListActivityV2::class.java)
                startActivity(intent)
            }
        }

    }

    fun getFormatDate():String{
        var format = SimpleDateFormat("yyyy-MM")
        return format.format(calendar.time)
    }

    override fun initData() {
    }

    fun validate(): Boolean {
        if (TvCheckType.text.isEmpty()) {
            toast("请选择点验类型")
            return false
        }
        if (TvCheckDate.text.isEmpty()) {
            toast("请选择点验日期")
            return false
        }
        if (EtCheckPerson.text.isEmpty()) {
            toast("请输入点验人员")
            return false
        }
        return true
    }

    class UploadItem(var id : String,var datetime : String,var state : String)
}